package com.sky.chapter2.Unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 *  description: 使用unsafe实现非阻塞原子性操作
 * Author by cqb, Date on 2020/10/2，12:49
 */
public class TestUnsafe {
    //1.获取unsafe实例对象
    static final Unsafe unsafe;
    //2.记录变量state在类TestUnsafe中的偏移值
    static final long stateOffset;
    //3.设置变量state的初始值
    private volatile long state=0;
    //4.获取变量state在类TestUnsafe中的偏移值
    static {
        try {
//            stateOffset=unsafe.objectFieldOffset(TestUnsafe.class.getDeclaredField("state"));
            //使用反射获取Unsafe的成员变量theUnsafe
            Field field=Unsafe.class.getDeclaredField("theUnsafe");
            //设置为可存取
            field.setAccessible(true);
            //获取该变量的值
            unsafe= (Unsafe) field.get(null);
            //获取state在TestUnsafe中的偏移量
            stateOffset =unsafe.objectFieldOffset(TestUnsafe.class.getDeclaredField("state"));
        }catch (Exception ex){
            System.out.println();

            throw new Error(ex);
        }
    }

    //5.在main方法中创建类TestUnsafe实例，并设置变量state值为1.
    public static void main(String[] args) {
        TestUnsafe test=new TestUnsafe();
        boolean success=unsafe.compareAndSwapInt(test, stateOffset,0,1);
        System.out.println(success);
    }
}
